package cn.iocoder.yudao.module.mqtt.service.user;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.mqtt.controller.admin.user.vo.*;
import cn.iocoder.yudao.module.mqtt.dal.dataobject.user.MedicalUserDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.mqtt.dal.mysql.user.MedicalUserMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.module.mqtt.enums.ErrorCodeConstants.*;

/**
 * 用户信息 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class MedicalUserServiceImpl implements MedicalUserService {

    @Resource
    private MedicalUserMapper userMapper;

    @Override
    public Long createUser(MedicalUserSaveReqVO createReqVO) {
        // 插入
        MedicalUserDO user = BeanUtils.toBean(createReqVO, MedicalUserDO.class);
        userMapper.insert(user);
        // 返回
        return user.getId();
    }

    @Override
    public void updateUser(MedicalUserSaveReqVO updateReqVO) {
        // 校验存在
        validateUserExists(updateReqVO.getId());
        // 更新
        MedicalUserDO updateObj = BeanUtils.toBean(updateReqVO, MedicalUserDO.class);
        userMapper.updateById(updateObj);
    }

    @Override
    public void deleteUser(Long id) {
        // 校验存在
        validateUserExists(id);
        // 删除
        userMapper.deleteById(id);
    }

    @Override
        public void deleteUserListByIds(List<Long> ids) {
        // 校验存在
        validateUserExists(ids);
        // 删除
        userMapper.deleteByIds(ids);
        }

    private void validateUserExists(List<Long> ids) {
        List<MedicalUserDO> list = userMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(USER_NOT_EXISTS);
        }
    }

    private void validateUserExists(Long id) {
        if (userMapper.selectById(id) == null) {
            throw exception(USER_NOT_EXISTS);
        }
    }

    @Override
    public MedicalUserDO getUser(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public PageResult<MedicalUserDO> getUserPage(MedicalUserPageReqVO pageReqVO) {
        return userMapper.selectPage(pageReqVO);
    }

}